import update from 'immutability-helper'
import type { FC } from 'react'
import { memo, useCallback, useState } from 'react'
import { useDrop } from 'react-dnd'

import { Card } from './Card'
import { ItemTypes } from './ItemTypes'
import Box from './Box'

const style = {
  width: 400,
}

export interface ContainerState {
  cards: any[]
}

const ITEMS = [
  {
    id: 1,
    text: 'Write a cool JS library',
  },
  {
    id: 2,
    text: 'Make it generic enough',
  },
  {
    id: 3,
    text: 'Write README',
  },
  {
    id: 4,
    text: 'Create some examples',
  },
  {
    id: 5,
    text: 'Spam in Twitter and IRC to promote it',
  },
  {
    id: 6,
    text: '???',
    list: [
      {
        id: 110,
        text: '110'
      },
      {
        id: 111,
        text: '111'
      },
      {
        id: 112,
        text: '112'
      },
    ]
  },
  {
    id: 7,
    text: 'PROFIT',
  },
]

export default memo(function Container() {
  const [cards, setCards] = useState(ITEMS)

  const findCard = useCallback(
    (id: string) => {
      
      const index = cards.findIndex((v:any)=>v.id==id)
      console.log('indexindex',cards,index,id)
      return {
        card:cards[index],
        index,
      }
    },
    [cards],
  )

  const moveCard = useCallback(
    (id: string, atIndex: number) => {
      debugger
      if (id) {
        const { card, index } = findCard(id)
       setCards(
          update(cards, {
            $splice: [
              [index, 1],
              [atIndex, 0, card],
            ],
          }),
       )
      } else {
        setCards(
          update(cards, {
            $splice: [
              [atIndex, 0],
              [atIndex + 1, 0, { id: Math.random(), text: `${cards.length}--lll` }],
            ],
          }),
        )
      }

    },
    [findCard, cards, setCards],
  )

  const [, drop] = useDrop(() => ({ accept: ItemTypes.CARD }))
  return (
    <div>
      <div ref={drop} style={style}>
        {cards.map((card,originalIndex) => (
          <Card
            item={card}
            originalIndex={originalIndex}
            moveCard={moveCard}
            findCard={findCard}
          />
        ))}
      </div>
      <Box />
    </div>

  )
})
